# ----------------------------------------------
#  tuff.py
#   try until fucking fail
# ----------------------------------------------
#  03_01Jan13 13xx ** initial
#  03_01Jan13 1413 ** added doctest
# ----------------------------------------------
#

class NotFound(Exception): pass

def default_fitness(f):
	# aka f != None
	return not not f
def default_catenator(a,b):
	# aka operator.add
	return a+b
def absolute_catenator(a,b):
	return b
def default_nf():
	raise NotFound

def tuff(i, l, fn, f=default_fitness, c=default_catenator, nf=default_nf):
	"""
	
>>> i='__init__'
>>> l=['.abc','.pyt','.py']
>>> def fitness(n): 
... 	return n!=None
>>> def n(m):
... 	fp = None
... 	try:
... 		fp = open(m,'rb')
... 	except IOError, e:
... 		pass
... 	return fp
>>> x=tuff(i,l,n)#default_fitness,default_catenator,default_nf)
>>> print 108,type(x),x.name
108 <type 'file'> __init__.py
"""
	# initial list function fitness catenator none-fit
	R=None
	I=fn(i)
	if not f(I):
		for each in l:
			I=fn(c(i,each))
			if f(I): R=I; break
		else:
			R=None
	else:
		R=I
	if R == None:
		nf()
	return R

# ---=---=---=---=---=---=---=---=---=---=---=---=---=---=---=---=---=

def _test():
	import doctest, tuff
	return doctest.testmod(tuff)

if __name__ == "__main__":
	_test()

#
# eof
#
